# -*- coding: utf-8 -*-
"""
__mktime__ = '2019/6/9'
__author__ = 'Just'
__filename__ = 'banner'
"""
from flask import jsonify
from app.libs.redprint import Redprint
from app.libs.error_code import Success, DeleteSuccess, NotFoundException
from app.libs.token_auth import auth
from app.model.banner import Banner
from app.model.banner_item import BannerItem
from app.model.base import db
from app.validators.form import BannerChangeForm, BannerDataForm, BannerDataDeleteForm
from app.viewmodel.banner import BannerCollection


api = Redprint('banner')


@api.route('', methods=['GET'])
@auth.login_required
def get_banners():
    """管理员获取获取banner列表"""
    banner_list = Banner.banners_for_admin()
    if not banner_list:
        raise NotFoundException(msg='暂无主题数据，请添加', error_code=2010)
    items = [x.items.all() for x in banner_list]
    collection = BannerCollection()
    collection.fill(list(zip(banner_list, items)))
    return jsonify(collection)


@api.route('', methods=['POST'])
@auth.login_required
def add_banner():
    """管理员添加新轮播广告位"""
    form = BannerChangeForm().validate_for_api()
    Banner.add_banner(form.data)
    return Success(code=201, msg='添加成功')


@api.route('/<int:bid>/update', methods=['POST'])
@auth.login_required
def update_banner(bid):
    form = BannerChangeForm().validate_for_api()
    Banner.update_banner(bid, form.data)
    return Success(code=201, msg='更新成功')


@api.route('/<int:bid>', methods=['DELETE'])
@auth.login_required
def remove_banner(bid):
    """管理员移除某Banner 也要删除其关联的数据记录"""
    banner = Banner.query.get_or_404(bid, msg='此id号 banner栏不存在', error_code=2000)
    ids = [item.id for item in banner.items.all()]
    with db.auto_commit():
        # 先删BannerItem表的记录，因为不是简单的关联关系
        if ids:
            db.session.query(BannerItem).filter(BannerItem.id.in_(ids)).delete(synchronize_session=False)
        db.session.delete(banner)
    return DeleteSuccess(msg='删除成功')


@api.route('/add_or_update', methods=['POST'])
@auth.login_required
def add_or_update_banner_data():
    """管理员给某个banner 添加/更新 一条BannerItem数据"""
    form = BannerDataForm().validate_for_api()
    banner = Banner.query.get_or_404(form.bid.data, msg='此id号 banner栏不存在', error_code=2000)
    titles = [item.title for item in banner.items.all()]
    if form.title.data not in titles:
        BannerItem().add_banner_item(form.data)
        return Success(code=201, msg='添加成功')
    else:
        BannerItem().update_banner_item(form.data)
        return Success(code=201, msg='更新成功')


@api.route('/delete', methods=['DELETE'])
@auth.login_required
def delete_banner_data():
    """管理员 删除 某个banner下 banner_item 一条/多条数据"""
    form = BannerDataDeleteForm().validate_for_api()
    bid = form.bid.data
    items_id = form.items.data  # list
    banner = Banner.query.get_or_404(bid, msg='此id号 banner栏不存在', error_code=2000)
    banner_items_id = [item.id for item in banner.items.all()]
    if not banner_items_id:
        raise NotFoundException(msg='这些BannerItem记录已不存在了', error_code=2004)
    items_id = list(set(items_id) & set(banner_items_id))  # 交集
    if not items_id:
        raise NotFoundException(msg='这些BannerItem记录已不存在了', error_code=2004)
    with db.auto_commit():
        db.session.query(BannerItem).filter(BannerItem.id.in_(items_id)).delete(synchronize_session=False)
    return DeleteSuccess(msg="删除成功")
